package com.dayuanit.dy17.mix.aop.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MethodProcessTimeAspect {
    //本地线程，可以将一些共享参数放到此对象中，且是线程安全的。
    private static final ThreadLocal<Long> timeThreadLocal = new ThreadLocal<>();

    @Pointcut("execution(* com.dayuanit.dy17.mix.aop.service.impl..*.*(..))")
    public void pointCut() {

    }

//    @Around("pointCut()")
//    public void doAround(ProceedingJoinPoint joinPoint) {
//        try {
//            long startTime = System.currentTimeMillis();
//            joinPoint.proceed();
//            long endTime = System.currentTimeMillis();
//            System.out.println("总耗时：" + (endTime - startTime));
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
//    }

    @Before("pointCut()")
    public void doBefore() {
        long startTime = System.currentTimeMillis();
        System.out.println("startTime=" + startTime + " thread=" + Thread.currentThread().getName());

        //将开始时间存放到当前线程中共享容器中
        timeThreadLocal.set(startTime);
    }

    @After("pointCut()")
    public void doAfter() {
        long endTime = System.currentTimeMillis();
        System.out.println("endTime=" + endTime+ " thread=" + Thread.currentThread().getName());
        //从本地线程当中，获取开始时间
        long startTime = timeThreadLocal.get();
        System.out.println("总耗时=" + (endTime - startTime));

        //用完之后，就将元素溢除，防止内存泄露
        timeThreadLocal.remove();
    }

}
